package com.zyy;

/**
 * @ProjectName: concurrent
 * @Package: com.zyy
 * @ClassName: HasInterruptedException
 * @Author: ZHAYUYAO
 * @Description: InterruptedException异常的时候如何安全中断
 * @Date: 2019/9/15 20:50
 * @Version: 1.0
 */
public class HasInterruptedException {
    static class Mythread extends Thread {
        public Mythread(String name) {
            super(name);
        }

        @Override
        public void run() {
            String currentThreadName = Thread.currentThread().getName();
            while (!isInterrupted()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    System.out.println(currentThreadName + " InterruptedException,interrupted flag is " + isInterrupted());
                    //这里是关键
                    interrupt();
                    e.printStackTrace();
                }
                System.out.println(currentThreadName + " is running");
            }
            System.out.println(currentThreadName + " interrupted flag is " + isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Mythread mythread = new Mythread("zyy");
        mythread.start();
        Thread.sleep(500);
        mythread.interrupt();

    }
}
